/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.storage.web;

import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.storage.dao.ActivityGoodsDao;
import com.jeesite.modules.storage.entity.Activity;
import com.jeesite.modules.storage.entity.ActivityGoodsSpec;
import com.jeesite.modules.storage.entity.GoodsSpec;
import com.jeesite.modules.storage.service.*;
import com.jeesite.modules.sys.utils.LogUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 营销活动Controller
 */
@Controller(value = "webactivity")
@RequestMapping(value = "${adminPath}/storage/activity")
public class ActivityController extends BaseController {

	@Autowired
	private ActivityService activityService;

	@Autowired
	private BrandService brandService;

	@Autowired
	private GoodsService goodsService;

	@Autowired
	private GoodsSpecService goodsSpecService;

	@Autowired
	private ActivityGoodsService activityGoodsService;

	@Autowired
	private ActivityGoodsDao activityGoodsDao;

	@Autowired
	private ActivityGoodsSpecService activityGoodsSpecService;
	
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public Activity get(String id, boolean isNewRecord) {
		return activityService.get(id, isNewRecord);
	}

	/**
	 * 查询列表
	 */
	@RequestMapping(value = {"list", ""})
	public String list(Activity activity, Model model) {
		model.addAttribute("activity", activity);
		model.addAttribute("brands", brandService.getAllList());
		return "modules/storage/activity/list";
	}

	/**
	 * 选择
	 */
	@RequestMapping(value = {"select", ""})
	public String select(Activity activity, Model model) {
		model.addAttribute("activity", activity);
		model.addAttribute("brands", brandService.getAllList());
		return "modules/storage/activity/select";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<Activity> listData(Activity activity, HttpServletRequest request, HttpServletResponse response) {
		activity.setPage(new Page<>(request, response));
		Page<Activity> page = activityService.findPage(activity);
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequestMapping(value = "form")
	public String form(Activity activity, Model model) {
		model.addAttribute("activity", activity);
		model.addAttribute("brands", brandService.getAllList());
		return "modules/storage/activity/form";
	}

	/**
	 * 保存营销活动
	 */
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated Activity activity) {
		try{
			activityService.save(activity);
			return renderResult(Global.TRUE, text("保存营销活动成功！"));
		}catch (Exception ex){
			return renderResult(Global.FALSE, text(ex.getMessage()));
		}
	}
	
	/**
	 * 删除营销活动
	 */
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(Activity activity) {
		try{
			activityService.delete(activity);
			return renderResult(Global.TRUE, text("删除营销活动成功！"));
		}catch (Exception ex){
			return renderResult(Global.FALSE, text(ex.getMessage()));
		}
	}

	/**
	 * 导出数据
	 */
	@RequestMapping(value = "exportData")
	public void exportData(HttpServletResponse response) {

	}

	/**
	 * 下载导入数据模板
	 */
	@RequestMapping(value = "importTemplate")
	public void importTemplate(HttpServletResponse response) {
		importTemplate(response,"活动 - 大仓库.xlsx");
	}

	/*
	 * 读取Excel到列表
	 */
	private List<Activity> readExcelToList(MultipartFile file){
		try {
			List<Activity> activities = new ArrayList<>();
			Workbook workbook = getWorkbook(file);
			Sheet sheet = workbook.getSheetAt(0);
			Activity activity = null;
			for (int rowNum = 2; rowNum <= sheet.getLastRowNum(); rowNum++) {
				Row row = sheet.getRow(rowNum);
				if (row == null  || row.getLastCellNum() < 15) {
					continue;
				}
				String name = getCellValue(row,3);
				if(StringUtils.isBlank(name)){
					continue;
				}
				String type = getCellValue(row,0);
				String brandId = getCellValue(row,4);
				Date startTime = new Date(getCellValue(row,5));
				Date endTime = new Date(getCellValue(row,6));

				Boolean isNew = activity == null || (!activity.getType().equals(type) || !activity.getBrandId().equals(brandId)|| !activity.getName().equals(name) || !activity.getStartTime().equals(startTime) || !activity.getEndTime().equals(endTime));
				if(isNew){
					activity = new Activity();
					activity.setType(type);
					activity.setSort(Integer.parseInt(getCellValue(row,1)));
					activity.setThumbnail(getCellValue(row,2));
					activity.setName(name);
					activity.setBrandId(brandId);
					activity.setStartTime(startTime);
					activity.setEndTime(endTime);
					activity.setPicture(getCellValue(row,7));
					activity.setIntroduction(getCellValue(row,8));
					activity.setShipping(getCellValue(row,9));
					activity.setFreeShipping(getCellValue(row,10));
					activity.setGoodsSpecList(new ArrayList<>());
				}
				ActivityGoodsSpec activityGoodsSpec = new ActivityGoodsSpec();
				activityGoodsSpec.setSort(activity.getGoodsSpecList().size() + 1);
				activityGoodsSpec.setCode(getCellValue(row,11));
				activityGoodsSpec.setSeckillPrice(Double.parseDouble(getCellValue(row,13)));
				activityGoodsSpec.setStockNum(Integer.parseInt(getCellValue(row,14)));
				activity.getGoodsSpecList().add(activityGoodsSpec);

				if(isNew){
					activities.add(activity);
				}
			}
			return activities;
		} catch (Exception ex) {
			throw ex;
		}
	}

	/*
	 * 读取Excel到列表
	 */
	private String check(List<Activity> activities){
		return "";
	}

	/**
	 * 导入数据
	 */
	@ResponseBody
	@PostMapping(value = "importData")
	public String importData(MultipartFile file) {
		try {
			List<Activity> activities = readExcelToList(file);
			String msg = check(activities);
			if(StringUtils.isNotBlank(msg)){
				return renderResult(Global.FALSE, "导入出错:" + msg);
			}
			for (Activity activity : activities){
				activity.setBrandId(brandService.getIdByName(activity.getBrandId()));
				activity.setId(activityService.getId(activity.getType(),activity.getBrandId(),activity.getName(),activity.getStartTime(),activity.getEndTime()));
				activity.setThumbnail("/userfiles/activity/" + activity.getThumbnail());
				String picture = activity.getPicture();
				if(StringUtils.isNotBlank(picture)){
					List<String> pictures = new ArrayList<>();
					for (String pic : picture.split(",")){
						pictures.add("/userfiles/activity/" + pic);
					}
					activity.setPicture(String.join("|",pictures));
				}
				for (ActivityGoodsSpec activityGoodsSpec : activity.getGoodsSpecList()){
					GoodsSpec goodsSpec = goodsSpecService.getByCode(activityGoodsSpec.getCode());
					if(goodsSpec!=null){
						activityGoodsSpec.setGoodsId(goodsSpec.getGoodsId());
						activityGoodsSpec.setGoodsSpecId(goodsSpec.getId());
					}
				}
				activityService.save(activity);
			}
			return renderResult(Global.TRUE,"导入成功");
		} catch (Exception ex) {
			return renderResult(Global.FALSE, "导入出错:" + ex.getMessage());
		}
	}
}